package com.beaven.imclient.fragment;

import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import com.beaven.imclient.R;
import com.beaven.imclient.activity.ChatActivity;
import com.beaven.imclient.adapter.SessionAdapter;
import com.beaven.imclient.base.BaseFragment;
import com.beaven.imclient.presenter.chat.SessionContract;
import com.beaven.imclient.presenter.chat.SessionPresenter;
import com.beaven.imclient.widget.DividerDecoration;
import com.beaven.model.model.db.Session;
import com.chad.library.adapter.base.BaseQuickAdapter;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 */
public class MessageFragment extends BaseFragment implements SessionContract.View {

  public static MessageFragment newInstance() {
    return new MessageFragment();
  }

  @Override protected int getLayoutId() {
    return R.layout.fragment_message;
  }

  private SessionContract.Presenter presenter;
  private SessionAdapter adapter;

  @Override protected void initView(View rootView) {
    super.initView(rootView);
    RecyclerView recycler_session = (RecyclerView) rootView.findViewById(R.id.recycler_session);
    adapter = new SessionAdapter(R.layout.item_session, getContext());
    recycler_session.setLayoutManager(new LinearLayoutManager(getContext()));
    recycler_session.addItemDecoration(
        new DividerDecoration(getContext(), DividerDecoration.VERTICAL_LIST));
    recycler_session.setAdapter(adapter);
    adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
      @Override public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        ChatActivity.show(getContext(), (Session) adapter.getData().get(position));
      }
    });
  }

  @Override protected void initData() {
    super.initData();
    setPresenter(new SessionPresenter(this));
  }

  @Override public void onResume() {
    super.onResume();
    presenter.subscribe();
  }

  @Override public void onPause() {
    super.onPause();
    presenter.subscribe();
  }

  @Override public void onHiddenChanged(boolean hidden) {
    super.onHiddenChanged(hidden);
    if (hidden) {
      presenter.unSubscribe();
    } else {
      presenter.subscribe();
    }
  }

  @Override public void setPresenter(SessionContract.Presenter presenter) {
    this.presenter = presenter;
  }

  @Override public void showList(List<Session> sessionList) {
    adapter.setNewData(sessionList);
  }
}
